/**
 * Description: 
 *	a plugin for store or restore form data easily
 *  now not support some html5 form elements yet 
 * 
 * Author: AndrewZhang
 * Date: 2011-01-18		 
 * version: 1.0
 * license: MIT style license
 */
;(function($) {
	var toJson = window.JSON && JSON.stringify || $.toJSON,
		
		parseJson = window.JSON && JSON.parse || $.evalJSON,
		
		tags = ['input', 'select', 'textarea'],
		
		unwanted_types = ['button', 'file', 'password', 'image', 'submit', 'reset'];
	
	if(typeof toJson !== 'function') 
		throw new Error('please import jquery-json or json2');
	
	if(typeof $.jStorage == 'undefined')
		throw new Error('please import jStorage plugin');
		
	var storeSer = $.jStorage;
	
	$.extend($.fn, {
		// save form status
		// excludes: an array which contains unwanted element id
		formStore: function(excludes) {		
			return this.each(function() {
				var $form = $(this),
					// as a namespace for storage
					storeNS = $form[0].id; 

				// if not form, do nothing
				if($form[0].tagName !== 'FORM') return;
				
                //获取所有input值 进行遍历
				var lastarr = {};
				$("input[type='text']").each(function () {
					lastarr[$(this).attr('id')] = $(this).val();
				})

				console.log(lastarr)
				var data = [];
				// organize data and store it
				$.each(lastarr,function(key, item) {
					var obj = {};
					obj.id = key;

					obj.value = item;
					data.push(obj);
				});
				storeSer.set(storeNS, ''); // clear first
				storeSer.set(storeNS, toJson(data));
			});
		},
		// restore form status
		formRestore: function() {
			return this.each(function() {
				var $form = $(this),
					storeNS = $form[0].id;
					
				if($form[0].tagName !== 'FORM') return;
				
				// if nothing is stored before, then do nothing
				var data = storeSer.get(storeNS, '');
				if(data === '') return;
				
				// convert stored data to json format
				data = parseJson(data);
				for(var i = 0, l = data.length; i < l; i++) {
					var item = data[i],
						el = $('#' + item.id)[0];
					
					// checkbox or radio
					if(item.checked) {
						el.checked = item.checked;
					// select
					} else if(item.selected) {
						for(var n = 0, k = item.selected.length; n < k; n++) {
							el.options[item.selected[n]].selected = true;
						}
					// other inputs
					} else {
						el.value = item.value;
					}
				}
			});
		},
		// delete form storage
		destroyStore: function() {
			return this.each(function() {
				var $form = $(this),
					storeNS = $form[0].id;
					
				if($form[0].tagName !== 'FORM') return;
				
				storeSer.deleteKey(storeNS);
			});
		}
	});	
})(window.jQuery);